import React from 'react';
import { toJS } from 'mobx';
import { Upload } from 'weaver-mobile-page';
import { observer, inject } from 'mobx-react';
import {withRouter, Route} from 'react-router-dom';
import { _,FieldUtil } from '../../util/pcPublic';
import { getLabel, showFormAttach } from '../../util/common';
import * as base from '../../util/base';
import * as emSDK from './../../util/emSDK';

@inject('wfGlobalStore', 'wfLayoutStore','wfOperateStore')
@withRouter
@observer
export default class FileElement extends React.Component{
    doChangeEvent(ids,filedatas){
        const { fieldMark,fieldObj,wfLayoutStore } = this.props;
        const specialobj = fieldObj.specialobj || {};
        filedatas.map(item=>{  delete item.buttonGroup;})
        specialobj.filedatas = filedatas;
        wfLayoutStore.changeSingleFieldValue(fieldMark, {value:ids.join(","), specialobj:specialobj});
    }


    render() {
        const { fieldMark,fieldValue,viewAttr,fieldAttr,symbol,rowIndex,isDetailShow,cellObj,fieldObj,wfGlobalStore ,wfLayoutStore} = this.props;
        const { isDetail,detailtype,fileattr } = fieldAttr;
        let specialobj  = fieldObj.specialobj ? toJS(fieldObj.specialobj) : {};
        const { filedatas, showBatchLoad } = specialobj; 
        const { markInfo = {},variableMap } = this.props.wfOperateStore;
        const { isannexupload_edit = false } = markInfo;
        //计算附件上传目录  catelogType = 0:固定目录 1：选择目录
        let category = "";
        let { catelogType,docCategory,selectedCateLog,maxUploadSize,limitType }  = fileattr;
        let errorMsg = "";
        if(catelogType === 0){
            if(_.trim(docCategory).length > 0){
                category = _.trim(docCategory);
            }else{ 
                errorMsg = getLabel(83157,"附件上传目录未设置!");
            }
        }else{
            const selectedCatalog = this.getFileSelectedCatalog();
            if(_.isEmpty(selectedCatalog)){
                errorMsg = getLabel(83157,"附件上传目录未设置!");
            }else{
                if(selectedCatalog.errorMsg){
                    errorMsg = selectedCatalog.errorMsg;
                }else{
                    category = selectedCatalog && selectedCatalog.docCategory;
                    maxUploadSize = selectedCatalog && selectedCatalog.maxUploadSize;
                }
            }
        }
        if(errorMsg !== "")
            return <span style={{color:"red"}}>{errorMsg}</span>
        const { commonParam } = wfGlobalStore;
        const { workflowid,requestid,authStr,authSignatureStr,f_weaver_belongto_userid,f_weaver_belongto_usertype,isviewonly } = commonParam;
        const baseRoute = isDetail && !isDetailShow ? "/req/editDetailRow" : "/req";
        let mobileWFOffice = variableMap.has("mobileWFOffice") ? variableMap.get("mobileWFOffice") : "0";
        const listType = detailtype === 2 ? "img" : "list";
        const uploadUrl = "/api/doc/upload/uploadFile2Doc";
        const uploadParams = {
            category,workflowid,listType,authStr,authSignatureStr,f_weaver_belongto_userid,f_weaver_belongto_usertype
        };
        let fileProps = { viewAttr,uploadUrl,uploadParams,category,listType,limitType,maxUploadSize };
        fileProps.uploadId = fieldMark;
        fileProps.imgColNumber = isDetailShow ? 1 : 3;
        filedatas && filedatas.map(item => {
            let check = emSDK.checkShowSignBtn(item.fileExtendName,viewAttr,isannexupload_edit);
            if (mobileWFOffice == 1 && !isDetailShow && isviewonly != 1&& check && emSDK.checkSigningBatch(viewAttr > 1, item.fileExtendName)) {
                let buttonGroup = [
                    {
                        label: item.fileExtendName == "pdf" ? getLabel(504662,"PDF签批") : getLabel(504594,"签批"),
                        buttonProps: {
                            onClick: () => {
                                emSDK.confirmSignType(item.imagefileid, item.fileid, item.filename, viewAttr, isannexupload_edit, true,  fieldObj.fieldStore);
                            }, 
                        },
                    }
                ]
                item.buttonGroup = buttonGroup 
            }
            if (item.fileExtendName != "pdf") {
                emSDK.changeFileid(item);
            }
        })
        fileProps.datas = filedatas;

        //拖拽参数调整
        const {isresetname = false, issortable = false} = fileattr
        if(isresetname && issortable) {
            fileProps["editable"] = true;
            let padding_style = {style:{padding :"0 5px"}};
            fileProps["selecButtonProps"] = { ...padding_style, ...fileProps.selecButtonProps};
            fileProps["showEditButtonProps"] ={...padding_style, ...fileProps.showEditButtonProps}  ;
            fileProps.uploadParams["isFirstUploadFile"] = "9";//存为流程草稿
            fileProps["store"] = isDetailShow ? fieldObj.fieldStore : fieldObj.fieldStoreEdit;
        }
        if(viewAttr == 1) {
            fileProps["editable"] = false;
        }
        //显示附件辅助字段
        const {showUploader, showUploadTime, showFullName, showFilesize} = fileattr
        fileProps["showUploader"] = showUploader;
        fileProps["showUploadTime"] = showUploadTime;
        fileProps["showFullName"] = showFullName;
        fileProps["showFilesize"] = showFilesize;
        return (
			<div>		
            <Upload
                {...fileProps}
                onChange={this.doChangeEvent.bind(this)}
                onItemClick={(file) =>{
                    const { detailtype } = this.props.fieldAttr;
                    showFormAttach(file, {}, baseRoute, detailtype);
                }}
            />
			 { fieldValue == '-2' && <p style={{color:'red'}}>附件已与正文相关联，请在正文中查看附件！</p>}
            </div>	
        )
    }
    //获取附件字段对应的选择框目录信息
    getFileSelectedCatalog(){
        const { rowIndex,fieldAttr,wfLayoutStore } = this.props;
        const { fileattr } = fieldAttr || {};
        const { fieldAttrMap } = wfLayoutStore;
        const selectedFieldid = fileattr.selectedCateLog;
        if(fileattr.catelogType !== 1 || !selectedFieldid || !fieldAttrMap.has(selectedFieldid))      //附件字段非选择框控制目录
            return {};

        const selectedFieldValue = FieldUtil.getRelateFieldValue(selectedFieldid, rowIndex);
        const selectedFieldAttr = fieldAttrMap.get(selectedFieldid);
        const { fieldlabel,selectattr } = selectedFieldAttr;

        let selectedCatalog = {};
        if(selectedFieldid !== "" && selectedFieldValue !== ""){
            selectattr && selectattr.selectitemlist.map(v =>{
                if(v && v.selectvalue.toString() === selectedFieldValue.toString())
                    selectedCatalog = {docCategory:v.docCategory, maxUploadSize:v.maxUploadSize||5};
            });
        }else{
        	selectedCatalog.errorMsg = getLabel(125389,'请先选择"') +fieldlabel+'"';
        }
        return selectedCatalog;
    }

    
  
}
